import Taro from "@tarojs/taro";
import { useLocationStore } from "../store";

export async function getLocation() {
  const locationStore = useLocationStore();
  await locationStore.getAllCitydata();
  Taro.getLocation({
    success: (res) => {
      locationStore.setLocation(res["latitude"], res["longitude"], res["city"]);
      const selectCityinfo = locationStore.selectCityinfo;
      if (!selectCityinfo) {
        return;
      }
      if (!res["city"].includes(selectCityinfo.cityName)) {
        // 如果当前获取的城市与已选择的城市不一致
        Taro.showModal({
          title: "位置更新",
          content: `是否切换城市为【${res["city"]}】`,
          success: (res) => {
            if (res.confirm) {
              locationStore.setSelectCityinfo(locationStore.currentCityinfo);
            }
          },
        });
      }
    },
    fail: (error) => {
      // console.log(error);
      setTimeout(() => {
        Taro.navigateTo({
          url: "/pages/select-city/index",
        });
      }, 500);
    },
    complete: (res) => {
      console.log(res);
    },
  });
}
